<template>
  <div class="loginMain">
    <div class="logo" @click="goIndex">
      <img src="@/assets/logo/logo.png" alt="Logo" class="logo-img">
    </div>
    <div class="loginBox" :class="{ 'slide-toggle': activeKey !== 'login' }">

      <div class="login-left" :class="{ 'reverse-order': activeKey !== 'login' }">
        <div class="text-container">
          <h3>欢迎使用</h3>
          <h1>渔吧</h1>
          <p>钓鱼人的交流网站</p>
        </div>
        <img width="350px" v-if="activeKey === 'login'" src="@/assets/images/fish.svg" alt="Logo"
          class="login-left-img">
        <img width="350px" v-else src="@/assets/images/login-bg-2.svg" alt="Logo" class="login-left-img">
      </div>

      <div class="login-right" :class="{ 'reverse-style': activeKey !== 'login' }">
        <a-tabs size="large" v-model:activeKey="activeKey" type="card">
          <a-tab-pane key="login" tab="登录">
          </a-tab-pane>
          <a-tab-pane key="register" tab="注册">
          </a-tab-pane>
        </a-tabs>
        <a-form :model="formState" name="normal_login" class="login-form" v-bind="layout" @finish="onFinish"
          @finishFailed="onFinishFailed">
          <a-form-item label="手机号" name="username" :rules="[{ required: true, message: '请输入手机号!' }]">
            <a-input v-model:value="formState.username">
              <template #prefix>
                <UserOutlined class="site-form-item-icon" />
              </template>
            </a-input>
          </a-form-item>

          <a-form-item label="密码" name="password" :rules="[{ required: true, message: '请输入密码!' }]">
            <a-input-password v-model:value="formState.password">
              <template #prefix>
                <LockOutlined class="site-form-item-icon" />
              </template>
            </a-input-password>
          </a-form-item>

          <a-form-item has-feedback label="验证码" name="captcha">
            <div style="display: flex; justify-content: space-between;">
              <a-input v-model:value="formState.captcha" style="width: 62%" />
              <img :src="codeUrl" style=" width: 80px;height: 40px;" class="login-code-img" @click="getCode" />
            </div>
          </a-form-item>

          <div class="form-item-box" v-if="activeKey==='login'">
            <a-checkbox style="margin-left: 15px;" v-model:checked="formState.remember">记住我</a-checkbox>
            <a class="login-form-forgot" @click="navigateToChangePassword">忘记密码?</a>
          </div>

          <a-button style="width: 100%; margin-top: 15px;" :disabled="!disabled || loading" type="primary"
            html-type="submit" class="login-form-button">
            <span v-if="!loading">{{ activeKey === 'login' ? '登 录' : '提 交' }}</span>
            <span v-else>{{ activeKey === 'login' ? '登 录 中...' : '注 册 中...' }}</span>
          </a-button>
        </a-form>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { reactive, computed, ref, onMounted, watch } from 'vue';
import { getCodeImg, register } from '@/api/login';
import { useUserStore } from '@/store/modules/user';
import { UserOutlined, LockOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { LoginData } from '@/api/types';
import { useRouter } from 'vue-router';
import { to } from 'await-to-js';

const activeKey = ref('login');

const router = useRouter();
const userStore = useUserStore();

const codeUrl = ref('');

const loginForm = ref<LoginData>({
  tenantId: '000000',
  username: 'admin',
  password: 'admin123',
  userType: 'front_user',
  grantType: 'password',
  rememberMe: false,
  code: '',
  uuid: '',
  clientId: import.meta.env.VITE_APP_CLIENT_ID
} as LoginData);
interface FormState {
  username: string;
  password: string;
  remember: boolean;
  captcha: string;
}
const formState = reactive<FormState>({
  username: '',
  password: '',
  remember: true,
  captcha: ''
});

const loading = ref(false);
//登录成功回调
const onFinish = async (values: any) => {
  if (activeKey.value === 'login') {
    loading.value = true;
    loginForm.value.username = values.username
    loginForm.value.password = values.password
    loginForm.value.code = values.captcha
    loginForm.value.rememberMe = values.remember

    try {
      const [err] = await to(userStore.login(loginForm.value));
      if (!err) {
        message.success('登录成功！');
        if (loginForm.value.rememberMe) {
          localStorage.setItem('tenantId', String(loginForm.value.tenantId));
          localStorage.setItem('username', String(loginForm.value.username));
          localStorage.setItem('password', String(loginForm.value.password));
          localStorage.setItem('rememberMe', String(loginForm.value.rememberMe));
        } else {
          localStorage.removeItem('tenantId');
          localStorage.removeItem('username');
          localStorage.removeItem('password');
          localStorage.removeItem('rememberMe');
        }

        //有点小呆，但不加又跳太快
        setTimeout(() => {
          router.go(-1)
          loading.value = false;
        }, 1200)
      } else {
        loading.value = false;
        // 重新获取验证码
        await getCode();
      }
    } catch (err: any) {
    }
  } else if (activeKey.value === 'register') {
    // 注册逻辑
    await onRegisterFinish(values);
  }
};

// 注册成功回调
const onRegisterFinish = async (values: any) => {
  loading.value = true;
  loginForm.value.username = values.username;
  loginForm.value.password = values.password;
  loginForm.value.code = values.captcha;

  try {
    const [err] = await to(register(loginForm.value));
    if (!err) {
      message.success('注册成功！');
      // 注册成功后可以选择自动登录或跳转到登录页面
      activeKey.value = 'login';

       // 重新获取验证码
       await getCode();
    } else {
       // 重新获取验证码
      await getCode();
    }
  } catch (err: any) {
    message.warning(err.message);
  } finally{
    loading.value = false;
  }
};

const getCode = async () => {
  const res = await getCodeImg();
  const { data } = res;

  codeUrl.value = 'data:image/gif;base64,' + data.img;
  loginForm.value.uuid = data.uuid;
}
const layout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 19 }
};


const goIndex = () => {
  router.replace('/social')
}

const navigateToChangePassword = () => {
  router.push({
    path: '/user/change-password',
  });
};

const onFinishFailed = (errorInfo: any) => {
  console.log('Failed:', errorInfo);
};
const disabled = computed(() => {
  return (formState.username && formState.password && formState.captcha);
});
onMounted(() => {
  getCode();
});

// 监听 activeKey 的变化
watch(activeKey, (newKey) => {
  // 清空表单数据
  formState.username = '';
  formState.password = '';
  formState.captcha = '';
  formState.remember = true;
});
</script>
<style scoped lang="scss">
:deep(.ant-input-password) {
  padding: 0;
}

:deep(.ant-input-password-icon) {
  margin-right: 0;
  height: 100%;
  display: flex;
  align-items: center;
}

:deep(.ant-input-affix-wrapper) {
  padding: 0 11px;
}

:deep(.ant-input-affix-wrapper-focused),
:deep(.ant-input-affix-wrapper:focus) {
  padding: 0 11px;
}

:deep(.ant-input-focused),
:deep(.ant-input:focus) {
  outline: none;
  box-shadow: none !important;
}

:deep(.ant-input-affix-wrapper-focused .ant-input) {
  width: 100%;
  outline: none;
}
.loginMain {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: url('@/assets/logo/login-bg.jpg') no-repeat;
  background-size: cover;

  .loginBox {
    padding: 30px;
    max-width: 948px;
    height: 500px;
    display: flex;
    justify-content: center;
    align-items: center;
    backdrop-filter: blur(5px);
    background-color: #fff;
    box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.37);
    -webkit-backdrop-filter: blur(5px);
    border-radius: 10px;
    border: 1px solid rgba(255, 255, 255, 0.18);

    .login-right {
      min-width: 410px;
      padding-left: 40px;
      position: relative;
      transition-timing-function: cubic-bezier(0.37, 0, 0.63, 1);
      transition: 1s;
      right: 0;
      background-color: #fff;

      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 5%;
        height: 95%;
        width: 2px;
        background: #e8e8e8;
      }

      &.reverse-style {
        padding-left: 0;
        padding-right: 40px;

        &::before {
          display: none;
        }

        &::after {
          content: '';
          position: absolute;
          right: 0;
          top: 5%;
          height: 95%;
          width: 2px;
          background: #e8e8e8;
        }
      }
    }

    .login-left {
      z-index: 1;
      position: relative;
      left: 0;
      transition-timing-function: cubic-bezier(0.37, 0, 0.63, 1);
      transition: 1s;
      height: 480px;
      padding: 30px 13px 30px 0;
      display: flex;
      background-color: #fff;

      &.reverse-order {
        flex-direction: row-reverse;
      }

      .text-container {
        h3 {
          color: #666;
          font-size: 24px;
          margin-bottom: 15px;
        }

        h1 {
          color: #333;
          font-size: 36px;
          font-weight: bold;
          margin-bottom: 10px;
        }

        p {
          color: #999;
          font-size: 14px;
        }
      }
    }
  }

  .slide-toggle {
    .login-left {
      left: 50%;
      background-color: #fff;
      z-index: 1;
    }
    .login-right{
      right: 50%;
      background-color: #fff;
    }
  }

  .form-item-box {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}

.captchaBox {
  display: flex;
}

.login-code {
  width: 33%;
  height: 40px;
  float: right;

  img {
    width: 87.25px;
    height: 100%;
    cursor: pointer;
    vertical-align: middle;
  }
}

.existsAccount {
  color: azure;
  cursor: pointer;
  padding-bottom: 10px;
}

.logo {
  position: absolute;
  top: 20px;
  left: 20px;
  cursor: pointer;

  .logo-img {
    width: 80px; // 根据实际Logo大小调整
  }
}
</style>
